package com.gitee.neuray.security.common.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: zhhongyu
 * @description: 导出操作
 * @since: Create in 14:55 2019/12/12
 */
@Slf4j
public class ExcelUtils {

    /**
     * 支持一行一列的单元格表头，获取单元格表头(复杂的单元格可对此方法进行扩充)
     *
     * @param jsonObject
     * @return
     */
    public static List<List<String>> getHeader(Map jsonObject) {
        List<List<String>> result = new ArrayList<>();
        jsonObject.forEach((key,value) ->{
            List<String> head = new ArrayList<>();
            head.add((String) value);
            result.add(head);
        });
        return result;
    }

    /**
     * 开始执行导入excel
     *
     * @param response    响应流
     * @param fileName    文件名称（中文已转码）
     * @param data        数据
     * @throws IOException
     */
    public static void export(HttpServletResponse response,
                       String fileName,
                       List data,
                       Class clazz) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        EasyExcel.write(outputStream, clazz).sheet("分页数据").doWrite(data);
    }
}
